/**
 * Author xiaol
 * Rev
 * Date: 2021-03-23 22:16
 * <p>
 * Copyright (C) 2021 Seeyon, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of Seeyon, Inc.
 * Use is subject to license terms.
 * @company seeyon.com
 * @author xiaol
 */
package com.lagou.scan;

import com.google.common.collect.Maps;
import com.lagou.SpringApplicationBoot;
import com.lagou.annotate.Service;
import com.lagou.bean.BeanDefinition;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * @description
 * @date 2021-03-23 22:16
 * @author xiaol
 */
public class PackageScanManagerImpl implements PackageScanManager{

	public Map<String, Class> scan(String scan) throws IOException, ClassNotFoundException {
		String[] value = scan.split(",");
		Map<String,Class> map = Maps.newHashMap();
		for (String packagePath : value) {
			String scanPath = packagePath.replaceAll("\\.", Matcher.quoteReplacement(File.separator));
			String path = SpringApplicationBoot.class.getResource("/").getPath() + scanPath;
			loadService(path,map);
		}
		return map;
	}

	private void loadService(String path, Map<String,Class> map) throws IOException, ClassNotFoundException {
		File file = new File(path);
		File[] files = file.listFiles();
		for (File file1 : files) {
			if(file1.isDirectory()){
				loadService(file1.getPath(),map);
			}else{
				String canonicalPath = file1.getCanonicalPath();
				String clazz = canonicalPath.split("classes\\\\")[1].split(".class")[0].replaceAll(Matcher.quoteReplacement(File.separator),"\\.");
				Class<?> aClass = Class.forName(clazz);
				if(aClass.isAnnotationPresent(Service.class)){
					Class<?>[] interfaces = aClass.getInterfaces();
					Arrays.asList(interfaces).forEach(iclass->{
						map.put(lowerFirstCase(iclass.getSimpleName()),aClass);
					});
				}
			}
		}
	}

	public static String lowerFirstCase(String str){
		char[] chars = str.toCharArray();
		chars[0] +=32;
		return String.valueOf(chars);
	}
}
